import 'package:flutter_module/http/hi_error.dart';
import 'package:flutter_module/http/hi_http.dart';
import 'package:flutter_module/http/request/base_request.dart';
import 'package:flutter_module/http/request/favorite_request.dart';
import 'package:flutter_module/http/request/recommend_request.dart';
import 'package:flutter_module/model/common_model.dart';
import 'package:flutter_module/page/base_page.dart';

class HiDao {
  HiDao._();

  static HiDao _instance;

  static HiDao getInstance() {
    if (_instance == null) {
      _instance = HiDao._();
    }
    return _instance;
  }

  var _cached = new Map();

  static const RECOMMENDS_SAVE_KEY = "RECOMMENDS_SAVE_KEY";
  static const FAVORITES_SAVE_KEY = "FAVORITES_SAVE_KEY";

  bool containCached(String key) {
    return _cached.containsKey(key);
  }

  //推荐接口 {}可选参数
  void recommends(BaseState state, Function(CommonModel) success,
      Function(HiError) error,
      {int pageIndex = 1, int PageSize = 10, bool needCached = false}) async {
    _send(RecommendReuest(), state, success, error,pageIndex: pageIndex,
        PageSize: PageSize, needCached: needCached);
  }

  //收藏接口 {}可选参数
  void favorites(BaseState state, Function(CommonModel) success,
      Function(HiError) error,
      {int pageIndex = 1, int PageSize = 10, bool needCached = false}) async {
    _send(FavoriteRequest(), state, success, error,pageIndex: pageIndex,
        PageSize: PageSize, needCached: needCached);
  }

  //私有的
  void _send(BaseRequest request, BaseState state,
      Function(CommonModel) success, Function(HiError) error,
      {int pageIndex = 1, int PageSize = 10, bool needCached = false}) async {
    var saveKey =
    request is RecommendReuest ? RECOMMENDS_SAVE_KEY : FAVORITES_SAVE_KEY;
    if (pageIndex == 1 && needCached && containCached(saveKey)) {
      success(_cached[saveKey]); //回调出去
    }
    request.add("pageIndex", pageIndex);
    request.add("pageSize", PageSize);

    try {
      var result = await HiHttp().fire(request);
      var model = CommonModel.fromJson(result);
      if (pageIndex == 1) {
        //下拉刷新 更新缓存
        _cached[saveKey] = model;
      }

      if (state != null && state.isDispose) return;
      success(model);
    } catch (e) {
      if (state != null && state.isDispose) return;
      error(e.message);
      print("hi-dao:${e.toString()}");
    }
  }
}
